﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace xKnight.WebCrawling.Core.HTTP
{
    public class HttpHelper
    {
        public static string GetTextBodyOfHttpResponse(HttpWebResponse httpWebResponse)
        {
            string response = null;

            using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(),Encoding.UTF8))
            {
                response = sr.ReadToEnd();
            }

            return response;
        }

        internal static Cookie[] GetCookiesOfHttpResponse(HttpWebResponse httpWebResponse)
        {
            List<Cookie> cookies = new List<Cookie>();

            for (int i = 0; i < httpWebResponse.Cookies.Count; i++)
                cookies.Add(httpWebResponse.Cookies[i]);
            
            return cookies.ToArray();
        }

        internal static RequestRedirectionResult HandleRequestRedirection(HttpWebRequest httpWebRequest,Cookie[] firstRequestCookies)
        {
            RequestRedirectionResult result = new RequestRedirectionResult();

            if (firstRequestCookies!=null)
            {
                for (int i = 0; i < firstRequestCookies.Length; i++)
                    result.AddCookies(firstRequestCookies);
            }
           
            httpWebRequest.AllowAutoRedirect = false;
            
            var endOfSequence = false;

            while (!endOfSequence)
            {
                endOfSequence = true;
                var response = httpWebRequest.GetResponse() as HttpWebResponse;

                result.AddResponse(response);
                result.AddCookies(HttpHelper.GetCookiesOfHttpResponse(response));

                if (response.Headers["Location"] != null)
                {
                    endOfSequence = false;
                    httpWebRequest = new HttpRequestBuilder()
                    .SetCookies(result.Cookies)
                    .SetCookieAware(true)
                    .SetUrl(response.Headers["Location"])
                    .SetHttpMethod("GET")
                    .SetKeepAlive(true)
                    .SetUserAgent(httpWebRequest.UserAgent)
                    .getHttpWebRequest();
                }
            }

            return result;
        }
    }
}
